package com.example.selfcontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.selfcontrol.config.Response;
import com.example.selfcontrol.entity.LikeOpt;
import com.example.selfcontrol.mapper.LikeOptMapper;
import com.example.selfcontrol.service.LikeOptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikeOptServiceImpl implements LikeOptService {
    @Autowired
    private LikeOptMapper likeOptMapper ;


    @Override
    public Response ClickLike(int articleId , int userId) {
        QueryWrapper<LikeOpt> wrapper = new QueryWrapper<>() ;
        wrapper.like("article_id",articleId).like("like_user",userId) ;
        LikeOpt find = likeOptMapper.selectOne(wrapper) ;

        if(find != null) {
            // 存在记录就反转状态
            int newState = find.getState() ^ 1 ;
            find.setUpdateTime(new Date());
            find.setState(newState);
            likeOptMapper.update(find,wrapper) ;
            return new Response(true,"200",newState) ;
        }else {
            LikeOpt tmp = new LikeOpt(0,articleId,1,userId,new Date() ,new Date()) ;
            likeOptMapper.insert(tmp) ;
        }

        return Response.ok() ;
    }

    @Override
    public boolean isLike(int userId , Long articleId) {
        QueryWrapper<LikeOpt> wrapper = new QueryWrapper<>() ;
        wrapper.eq("article_id",articleId).eq("like_user",userId).eq("state",1) ;
        LikeOpt find = likeOptMapper.selectOne(wrapper) ;

        if(find != null)    return true ;
        return false ;
    }

    @Override
    public int CountLike(Long articleId) {
        QueryWrapper<LikeOpt> wrapper = new QueryWrapper<>() ;
        wrapper.eq("article_id",articleId).eq("state",1);
        return likeOptMapper.selectCount(wrapper) ;
    }
}
